package simpledemo1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @Description :
 * @FileName: EchoServerHandler.java
 * @Author :WeiHui.Zhang
 * @Data : 2016年2月16日 下午8:08:08
 * @Version:V1.00
 */
public class EchoServerHandler extends ChannelHandlerAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(EchoServerHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		LOG.info("channelRead");

		ByteBuf buffer = (ByteBuf) msg;
		byte[] req = new byte[buffer.readableBytes()];

		buffer.readBytes(req);

		String body = new String(req, "UTF-8");

		System.out.println(body + "->server");

		// 将服务器端的当前时间发送到client
		String currentTime = String.valueOf(System.currentTimeMillis());

		ByteBuf response = Unpooled.copiedBuffer(currentTime.getBytes());

		ctx.write(response);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		LOG.info("channelReadComplete");
		System.out.println("server send message....");
		ctx.flush();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		LOG.info("channelActive");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		LOG.info("channelInactive");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// super.exceptionCaught(ctx, cause);
		LOG.info("exceptionCaught : {}" + cause);
		ctx.close();
	}

}
